﻿using System;
using System.Threading;
using System.Windows.Threading;

namespace NanoMvvm
{
    public class SynchronizationHelper
    {
        private WeakReference<SynchronizationContext> currentRef;

        internal SynchronizationHelper()
        {
            AssignCurrentThreadAsMain();

            Initial = SynchronizationContext.Current;
        }

        /// <summary>
        /// Gets the primary UI <see cref="SynchronizationContext"/> to use in the framework.
        /// </summary>
        public SynchronizationContext Initial { get; private set; }

        /// <summary>
        /// Gets the current UI <see cref="SynchronizationContext"/> used by the framework.
        /// </summary>
        public SynchronizationContext Main
        {
            get
            {
                // for designer support
                if (Initial == null)
                {
                    AssignCurrentThreadAsMain();
                }

                return currentRef.IsTargetAlive ? currentRef.Target : null;
            }
            private set
            {
                if (value == null)
                {
                    throw new ArgumentNullException("value");
                }

                currentRef = new WeakReference<SynchronizationContext>(value);
            }
        }

        public void AssignCurrentThreadAsMain()
        {
            EnsureSynchronizationContext();

            Main = SynchronizationContext.Current;
        }

        public void AssignCurrentThreadAsInitial()
        {
            EnsureSynchronizationContext();

            Initial = SynchronizationContext.Current;
        }

        public void RevertToInitialSynchronization()
        {
            Main = Initial;
        }

        /// <summary>
        /// Ensures the existence of a <see cref="SynchronizationContext"/> on the current thread.
        /// </summary>
        private void EnsureSynchronizationContext()
        {
            if (SynchronizationContext.Current == null)
            {
                var context = new DispatcherSynchronizationContext(Dispatcher.CurrentDispatcher);
                SynchronizationContext.SetSynchronizationContext(context);
            }
        }
    }
}